package tgc.edu.yzy.web.controller;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.yzy.custom.Custom;
import tgc.edu.yzy.custom.JpgridUtils;
import tgc.edu.yzy.custom.JqgridParam;
import tgc.edu.yzy.entity.EimAdmin;
import tgc.edu.yzy.entity.EimInvoice;
import tgc.edu.yzy.entity.EimRegister;
import tgc.edu.yzy.entity.EimRole;
import tgc.edu.yzy.entity.EimUser;
import tgc.edu.yzy.entity.TradingRecord;
import tgc.edu.yzy.repostory.EimRegisterRepository;
import tgc.edu.yzy.security.User2;
import tgc.edu.yzy.service.AdminService;
import tgc.edu.yzy.service.AdministatorService;
import tgc.edu.yzy.service.InvoiceService;
import tgc.edu.yzy.service.RecordService;
import tgc.edu.yzy.service.RoleService;
import tgc.edu.yzy.service.TradingRecordService;
import tgc.edu.yzy.service.UserService;
import tgc.edu.yzy.web.form.UserForm;

@Controller
@RequestMapping(value="/less")
public class LesseeController {
	@Autowired
	private AdminService admin;
	@Autowired
	private AdministatorService admini;
	@Autowired
	private UserService userservice;
	
	@Autowired
	private RecordService recordservice;
	@Autowired
	private Custom custom;
	
	@Autowired
	private TradingRecordService tradingservice;
	
	@Autowired
	private InvoiceService invo;
	
	@Autowired
	private RoleService roleDAO;
	@Autowired
	private EimRegisterRepository eimregi;
	
	
	@RequestMapping(value="/user")
	public String user() {
		return "home/views/lessuser";
	}
	/***
	 * Ajax 获取所有用户的json
	 * @param param
	 * @return
	 */
	@RequestMapping(value="/userlist")
	@ResponseBody
	private Object list(JqgridParam param) {
		Pageable pageable = param.buildPageable();
		Page<EimUser> page=null;
		SecurityContext ctx = SecurityContextHolder.getContext();
		Authentication auth = ctx.getAuthentication();
		User2 user = (User2) auth.getPrincipal();
		EimAdmin Id = admin.findById(user.getId());
		if(!param.getSearch()) {
			page=userservice.findByEimadmins(pageable, Id);
		}else {
			String q=(param.getFilters()).substring(0,(param.getFilters()).length()-2);
			q=q+",{\"field\":\"eimadminids\",\"op\":\"eq\",\"data\":\""+user.getId()+"\"}]}";
			param.setFilters(q);
			page=userservice.findAll(param.buildSpec(), pageable);
		}
		HashMap<String , Object> result = JpgridUtils.getPageResult(page);
		return result;
	}
	/***
	 * 新增用户
	 * @param request
	 * @param id
	 * @param form
	 * @return
	 */
	@RequestMapping(value="/useradd")
	private String add(HttpServletRequest request,String id,UserForm form) {
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		EimUser user=new EimUser();
		BeanUtils.copyProperties(form, user);
		user.setPassword(encoder.encode("111111"));
		
		Integer ad= custom.getUser2();
		EimAdmin eimadmin=admin.findById(ad);
		user.setEimadmins(eimadmin);
		user.setMaxdate(eimadmin.getMaxdate());
		int a=3;
		EimRole op=roleDAO.findById(a);
		String uu=eimadmin.getId()+"";
		user.setEimadminids(uu);
		user.getRoles().add(op);
		userservice.save(user);
		String operation="新增";
		String content=eimadmin.getName()+"新增用户："+form.getName();
		custom.record(request, operation, content);
		return "home/views/lessuser";
	}
	
	//修改
	@RequestMapping(value="/useredit")
	@ResponseBody
	public Object edit(HttpServletRequest request,String id,UserForm form) {
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		String oper =form.getOper();
		if("del".equals(oper)) {
			EimUser uu=userservice.findById(Integer.parseInt(id));
			List<EimInvoice> inv=invo.findByEimuser(uu);
			for (EimInvoice e : inv) {
				e.setEimuser(null);
				invo.save(e);
			}
			String operation="删除";
			String content=uu.getEimadmins().getName()+"删除用户："+uu.getName();
			custom.record(request, operation, content);
			
			userservice.deleteByID(Integer.parseInt(id));
		}else if("add".equals(oper)) {
			//jqGrid里的新增已经删除了
			/*EimUser user=new EimUser();
			BeanUtils.copyProperties(form, user);
			user.setPassword(encoder.encode("111111"));
			
			Integer ad= custom.getUser2();
			EimAdmin eimadmin=admin.findById(ad);
			user.setEimadmins(eimadmin);
			user.setMaxdate(eimadmin.getMaxdate());
			int a=3;
			EimRole op=roleDAO.findById(a);
			String uu=eimadmin.getId()+"";
			user.setEimadminids(uu);
			user.getRoles().add(op);
			userservice.save(user);
			String operation="新增";
			String content=eimadmin.getName()+"新增用户："+form.getName();
			custom.record(request, operation, content);
			return "";*/
		}else {
			EimUser user=userservice.findById(Integer.parseInt(id));
			form.setUsername(user.getUsername());
			BeanUtils.copyProperties(form, user);
			
			Integer ad= custom.getUser2();
			EimAdmin eimadmin=admin.findById(ad);
			user.setEimadmins(eimadmin);
			user.setMaxdate(eimadmin.getMaxdate());
			
			String operation="修改";
			String content=eimadmin.getName()+"修改用户："+form.getName();
			custom.record(request, operation, content);
			
			userservice.save(user);
		}
		return "随意输入";
	}
	/***
	 * 修改密码
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/password")
	@ResponseBody
	public String password(HttpServletRequest request,Integer id) {
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		EimUser u=userservice.findById(id);
		u.setPassword(encoder.encode("111111"));
		String operation="重置密码";
		String content="用户："+u.getName()+"的密码被重置";
		custom.record(request, operation, content);
		userservice.save(u);
		return u.getName()+" 密码重置成功，重置后密码为111111";
	}
	
	//租户管理员对发票进行的管理
	@RequestMapping(value="/invoice")
	public String invoice() {
		return "home/views/invoice";
	}
	/***
	 * 显示所有发票信息
	 * @param param
	 * @return
	 */
	@RequestMapping(value="/invoicelist")
	@ResponseBody
	private Object invoicelist(JqgridParam param) {
		Pageable pageable = param.buildPageable();
		Page<EimInvoice> page=null; 
		SecurityContext ctx = SecurityContextHolder.getContext();
		Authentication auth = ctx.getAuthentication();
		User2 user = (User2) auth.getPrincipal();
		EimAdmin Id = admin.findById(user.getId());
		if(!param.getSearch()) {
			page=invo.findByEimadmin(pageable, Id);
		}else {
			String q=(param.getFilters()).substring(0,(param.getFilters()).length()-2);
			q=q+",{\"field\":\"eimadminids\",\"op\":\"eq\",\"data\":\""+user.getId()+"\"}]}";
			param.setFilters(q);
			page=invo.findAll(param.buildSpec(), pageable);
		}
		HashMap<String , Object> result = JpgridUtils.getPageResult(page);
		return result;
	}
	/***
	 * 发票修改
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/invoiceedit")
	@ResponseBody
	public Object invoiceedit(HttpServletRequest request,String id) {
		invo.deleteByID(Integer.parseInt(id)); 
		String operation="删除";
		String content="发票被删除";
		custom.record(request, operation, content);
		EimAdmin adminuu=admin.findById(custom.getUser2());
		Integer managed = adminuu.getManaged();
		Integer manage=managed-1;
		adminuu.setManaged(manage);
		admin.save(adminuu);
		return "ok";
	}
	//查看授权记录
	@RequestMapping(value="/recorde")
	public String recorde() {
		return "home/views/recorde";
	}
	/***
	 * 记录
	 * @param param
	 * @return
	 */
	@RequestMapping(value="/recordelist")
	@ResponseBody
	private Object recordelist(JqgridParam param) {
		Pageable pageable = param.buildPageable();
		Page<TradingRecord> page=null; 
		SecurityContext ctx = SecurityContextHolder.getContext();
		Authentication auth = ctx.getAuthentication();
		User2 user = (User2) auth.getPrincipal();
		EimAdmin Id = admin.findById(user.getId());
		if(!param.getSearch()) {
			page=tradingservice.findByEimadmins(pageable, Id);
		}else {
			page=tradingservice.findAll(param.buildSpec(), pageable);
		}
		HashMap<String , Object> result = JpgridUtils.getPageResult(page);
		return result;
	}
	@RequestMapping(value="delecte")
	private String delecte() {
		invo.deleteByEimadmin_id(custom.getUser2());
		EimAdmin ads=admin.findById(custom.getUser2());
		ads.setManaged(0);
		admin.save(ads);
		return "home/views/invoice";
	}
	//load新增的的页面
	@RequestMapping(value="goadd")
	private String goadd() {
		return "home/views/goadd";
	}
	
	@RequestMapping(value="/usernoandyes")
	@ResponseBody
	private Boolean usernoandyes(String username) {
		EimRegister a=eimregi.findByUsername(username);
		if(a!=null) {
			return false;
		}else {
			return true;
		}
	}
	/***
	 * 显示用户权限
	 * @return
	 */
	@RequestMapping(value="/userpower")
	private String userpower(ModelMap map,String pagesize) {
		Integer pagesize1;
		try {
			pagesize1=Integer.parseInt(pagesize);
		}catch (Exception e) {
			pagesize1=10;
		}
		if(pagesize1<=0||pagesize1==null) {
			pagesize1=10;
		}
		map.put("pagesize",pagesize1);
		return "home/views/userpower";
	}
	//ajax提交获取每页的数据
	@RequestMapping(value="/powerlist")
	@ResponseBody
	private Object powerlist(ModelMap map,Integer pageindex,Integer pagesize) {
		Pageable pageable=PageRequest.of((pageindex-1), pagesize);
		Page<EimUser> users=userservice.findByEimadmins(pageable,admin.findById(custom.getUser2()));
		return users;
	}
	//获取数据长度  新增权限
	@RequestMapping(value="/powerpage")
	@ResponseBody
	public Object powerpage() {
		long uu=userservice.countByEimadmins(admin.findById(custom.getUser2()));
		return uu;
	}
	@RequestMapping(value="/powerup")
	@ResponseBody
	public Object powerup(HttpServletRequest request,Integer id) {
		EimUser eim=userservice.findById(id);
		eim.setQl("1");
		userservice.save(eim);
		custom.record(request, "修改权限", eim.getName()+"拥有修改发票的");
		return "ok";
	}
	/*****
	 * 删除权限
	 */
	@RequestMapping(value="/powerdown")
	@ResponseBody
	public Object powerdown(HttpServletRequest request,Integer id) {
		EimUser eim=userservice.findById(id);
		eim.setQl(null);
		userservice.save(eim);
		custom.record(request, "修改权限", eim.getName()+"的权限丢失");
		return "ok";
	}
}
